package com.harvest.scientific.ladder.page

import android.graphics.Color
import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import com.harvest.scientific.ladder.base.BaActivity
import com.harvest.scientific.ladder.databinding.ActSpaBinding
import com.harvest.scientific.ladder.ext.launchOnMain
import com.harvest.scientific.ladder.util.SpUtil
import com.harvest.scientific.ladder.util.StbarUtil
import com.harvest.scientific.ladder.util.VcUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch

class SpaActivity : BaActivity(){

    private lateinit var binding: ActSpaBinding
    private var countDownJob: Job? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StbarUtil.setStatusBar(this,false, Color.TRANSPARENT,true)
        binding = ActSpaBinding.inflate(layoutInflater)
        setContentView(binding.root)
//        FirebaseCrashlytics.getInstance().setUserId(SpUtil.getUserId())

        initEvent()
        countDown(1000, 0, {}, {
            launchOnMain {
                HomeActivity.jump(this@SpaActivity, 0)
                finish()
            }
        }, {
        }, {})
    }

    private fun initEvent() {
        binding.tvProtocol.setOnClickListener {
            if (VcUtil.isFastDoubleClick(it)){
                return@setOnClickListener
            }
            countDownJob?.cancel()
            WebViewActivity.jumProtocol(this@SpaActivity)
            finish()
        }
    }


    fun countDown(
        timeMillis: Long = 1000,
        time: Int = 60,
        start: (scope: CoroutineScope) -> Unit,
        end: () -> Unit,
        next: (time: Int) -> Unit,
        error: (msg: String?) -> Unit
    ) {
        countDownJob = lifecycleScope.launch {
            flow {
                (time downTo 1).forEach {
                    delay(timeMillis)
                    emit(it)
                }
            }.onStart {
                start(this@launch)
            }.onCompletion {
                end()
            }.catch {
                error(it.message)
            }.collect {
                next(it)
            }
        }
    }
}